package com.bclz.netty.project;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

public class NettyClient {


    private NettyClient(){}

    public static void start(String inetHost, int inetPort){

        EventLoopGroup workerGroup=new NioEventLoopGroup();
        Bootstrap bootstrap=new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ClientInboundChannelHandle());
                    }
                });

        try {
            ChannelFuture channelFuture = bootstrap.connect(inetHost, inetPort).sync();
            Channel channel = channelFuture.channel();
            Scanner scanner=new Scanner(System.in);
            while (scanner.hasNext()){
                String next = scanner.next();
                channel.writeAndFlush(Unpooled.copiedBuffer(next, CharsetUtil.UTF_8));
            }
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("Client error...");
        }finally {
            workerGroup.shutdownGracefully();
        }

    }


}
